<template>
  <!-- 采购订单 列表页面-->
  <div class="app-container jklis">
    <el-form :model="queryParams" ref="queryForm" :inline="true" class="search-form-new">
      <el-form-item el-form-item label="店铺" prop="status" v-hasPermi="['searchTenantID']">
        <el-select v-model="queryParams.tenantId" placeholder="请选择店铺" clearable filterable size="small">
          <el-option v-for="dict in tenantList" :key="dict.tenantId" :label="dict.tenantName" :value="dict.tenantId" />
        </el-select>
      </el-form-item>
      <el-form-item label="供货商" prop="supplyChannel">
        <el-input v-model="queryParams.supplyChannel" placeholder="请输入供货商" clearable />
      </el-form-item>
      <el-form-item label="订单号" prop="no">
        <el-input v-model="queryParams.no" placeholder="请输入订单号" clearable />
      </el-form-item>
      <el-form-item label="商品编号" prop="goodsId">
        <el-input v-model="queryParams.goodsId" placeholder="请输入商品编号" clearable />
      </el-form-item>
      <el-form-item label="游戏账号" prop="realAccountNumber">
        <el-input v-model="queryParams.realAccountNumber" placeholder="请输入游戏账号" clearable/>
      </el-form-item>
      <el-form-item label="创建时间" prop="">
        <el-date-picker style="width: 300px;" clearable v-model="timer1" value-format="yyyy-MM-dd" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="支付时间" prop="">
        <el-date-picker clearable v-model="timer2" value-format="yyyy-MM-dd" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item> -->
      <el-form-item label="完成时间" prop="">
        <el-date-picker style="width: 300px;" clearable v-model="timer3" value-format="yyyy-MM-dd" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="销售渠道" prop="qudao">
        <el-select v-model="queryParams.qudao" placeholder="请选择渠道" clearable filterable>
          <el-option v-for="(item,key) in qudaoList" :key="key" :label="item.name" :value="item.name" />
        </el-select>
      </el-form-item>
      <el-form-item label="销售单号" prop="danhao">
        <el-input v-model="queryParams.danhao" placeholder="请输入销售单号" clearable size="small" />
      </el-form-item>
      <el-form-item class="btns">
        <el-button type="primary" icon="el-icon-search" @click="getList">搜索</el-button>
        <el-button icon="el-icon-refresh" type="warning" @click="resetQuery">重置</el-button>
        <!-- <el-button
          icon="el-icon-download"
          type="primary"
          size="small"
          @click="exportOrder"
          class="zdy-btn zdy-btn-refresh"
          >导出</el-button
        > -->
      </el-form-item>
    </el-form>
    <div class="zdy-main customTab customTabNew">
      <div class="tabs flex alc">
        <el-radio-group v-model="actived" @change="tabChange">
          <el-radio-button :label="tab.value" v-for="tab in commonMaps.orderStatusArr" :key="tab.value">{{ tab.name }}</el-radio-button>
        </el-radio-group>
        <!-- <div class="tongji_box" v-if="totalNumber">
          <span>
            总实付金额:
            <span class="price">{{ formatter(totalNumber.buyerActualAmountSum||0) }}</span>元
          </span>
          <span v-if="totalNumber.profileSum">
            总利润:
            <span class="price">{{ formatter(totalNumber.profileSum||0) }}</span>元
          </span>
        </div> -->
      </div>
      <div class="table_box table_box_new" style="margin-top: 10px;">
        <el-table border :data="tableData.records"  stripe>
      
          <el-table-column prop="no" label="订单编号" min-width="120">
            <template slot-scope="scope">
              <span class="link" @click="goOrderDetail(scope.row)">{{ scope.row.no }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="orderStatus" label="订单状态" width="100">
            <template slot-scope="scope">
                  <div>
                    <el-tag :type="commonMaps.orderStatusMapType[scope.row.orderStatus].type">{{scope.row.orderStatus?commonMaps.orderStatusMapType[scope.row.orderStatus].label:'无'}}</el-tag>
                  </div>
                </template>
          </el-table-column>
          <el-table-column prop="supplyTenantName" label="供货商" min-width="130"> </el-table-column>
          <el-table-column prop="createTime" label="创建时间" min-width="160"></el-table-column>
          <el-table-column prop="goodsId" label="商品编号" min-width="120"></el-table-column>
          <el-table-column prop="gameName" label="游戏名称" min-width="120"></el-table-column>
          <el-table-column prop="platformAmount" label="商品原价" min-width="100"></el-table-column>
          <el-table-column prop="saleAmount" label="折扣价格" min-width="100"></el-table-column>
          <el-table-column prop="guaranteeAmount" label="包赔费" width="150">
            <template slot-scope="scope">
              <span v-if="scope.row.guaranteeAmount&&scope.row.guaranteeAmount>0">
                <span>{{ scope.row.guaranteeAmount }}元</span><br />
                <span v-if="scope.row.guaranteeType">{{ scope.row.guaranteeType }}</span>
              </span>
              <span v-else>不买包赔</span>
            </template>
          </el-table-column>
          <el-table-column prop="actualAmount" label="实付金额" min-width="100"></el-table-column>
          <el-table-column prop="payTime" label="支付时间" min-width="160"></el-table-column>
          <el-table-column prop="finishTime" label="完成时间" min-width="160"></el-table-column>
          <el-table-column prop="" label="支付状态" min-width="100">
            <template slot-scope="scope">
              <el-tag type="danger" v-if="scope.row.salePay==1">
                未支付
              </el-tag>
              <el-tag type="success" v-if="scope.row.salePay==2">
                已支付
              </el-tag>
              <br />
              <span class="link" @click="openShouhou(scope.row)" v-if="scope.row.afterSaleState">售后{{scope.row.afterSaleState?commonMaps.afterOrderStateMap[scope.row.afterSaleState]:''}} <br /></span>
              
            </template>
          </el-table-column>
          <el-table-column prop="" label="发货状态" width="100">
            <template slot-scope="scope">
              <el-tag type="danger" v-if="scope.row.sendState==1">
                未发货
              </el-tag>
              <el-tag type="success" v-if="scope.row.sendState==2">
                已发货
              </el-tag>
            </template>
          </el-table-column>

          <!-- 销售信息 -->
          <el-table-column prop="qudao" label="销售渠道" ></el-table-column>
          <el-table-column prop="danhao" label="销售单号" ></el-table-column>
          <el-table-column prop="jietu" label="销售截图" >
            <template slot-scope="scope">
              <img-box :img="scope.row.jietu" width="50px" :height="50"></img-box>
            </template>
          </el-table-column>

          <!-- <el-table-column prop="" label="买家结算状态" min-width="80">
                <template slot-scope="scope">
                  <span>
                    <el-tag :type="commonMaps. saleSettlementStateMap[scope.row.saleSettlementState].type">{{
                    commonMaps.saleSettlementStateMap[scope.row.saleSettlementState].label || commonMaps. saleSettlementStateMap["1"].label
                  }}</el-tag>
                  </span>
                </template>
              </el-table-column> -->
          

          <el-table-column label="操作" min-width="200" fixed="right">
            <template slot-scope="scope">
              <el-button type="add" v-if="checkPermi(['caigou:payNow']) &&(scope.row.orderStatus == 3||scope.row.orderStatus == 4)&&scope.row.salePay == 1" @click="goOrderDetail(scope.row)">立即支付</el-button>
              <el-button type="edit" @click="openIM(scope.row.supplyTenantId)">联系卖家</el-button>
              <el-button type="del" v-if="scope.row.orderStatus != 2&&scope.row.salePay==1&&checkPermi(['orderForTenant:cancelOrder'])" @click="cancelOrder(scope.row)">取消交易</el-button>
              <el-button v-if="scope.row.sendState == 2&&scope.row.orderStatus == 4&&(!scope.row.afterSaleState||(scope.row.afterSaleState&&scope.row.afterSaleState!=3))" type="add" @click="completion(scope.row)">确认收货</el-button>
              <el-button  type="text" @click="openSaleInfo(scope.row)">销售信息</el-button>
              <!-- 申请售后：订单是汇付支付的，交易中不能申请；订单不是汇付的，交易中已支付状态可以申请。 -->
              <el-button type="text" @click="afterSale(scope.row)" v-if="(scope.row.orderStatus==4&&scope.row.isHuifu!=2&&scope.row.salePay==2&&scope.row.afterSaleState!=3)||(scope.row.orderStatus==1&&scope.row.afterSaleState!=3&&scope.row.salePay==2)">申请售后</el-button>
              <el-button type="text" @click="afterSaleView(scope.row.id)" v-if="actived=='101'">查看售后</el-button>
              <el-button v-if="scope.row.orderStatus == 2&&scope.row.salePay==2&&(!scope.row.claimRecordId)" type="text" @click="addPeifuFn(scope.row)">申请赔付</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="tableData.total > 0" :total="tableData.total" :page.sync="queryParams.pageNum"  :limit.sync="queryParams.pageSize" @pagination="getList" />
      </div>

      <!-- <el-tabs type="border-card" v-model="actived" @tab-click="tabChange" v-loading="loading">
        <el-tab-pane :label="item.name" :name="item.value" v-for="(item, key) in commonMaps.orderStatusArr" :key="key">
          
        </el-tab-pane>
      </el-tabs> -->
    </div>

    <h5Dialog ref="h5Dialog"></h5Dialog>
    <cancelOrderSure ref="cancelOrderSure"></cancelOrderSure>
    <orderDetailDialog ref="orderDetailDialog"></orderDetailDialog>
    <querenshouhuo ref="querenshouhuo"></querenshouhuo>
    <editPrice ref="editPrice"></editPrice>
    <payEdit ref="payEdit"></payEdit>
    <!-- <msgHistory ref="msgHistory" :showDialog="showMsgHis" @close="guanbi" :sessionId="toGroups"></msgHistory> -->
    <!-- <sendGoodsDialog ref="sendGoodsDialog" ></sendGoodsDialog> -->
    <afterSellAdd ref="afterSellAdd"></afterSellAdd>
    <afterSellViewBuyer ref="afterSellViewBuyer"></afterSellViewBuyer>
    <editRemarkDialog ref="editRemarkDialog"></editRemarkDialog>
    <kefuList ref="kefuList"></kefuList>

    <peifuAdd ref="peifuAdd"></peifuAdd>
    <caiGouShouHouMX ref="caiGouShouHouMX"></caiGouShouHouMX>
    <caigouXiaoshouInfo ref="caigouXiaoshouInfo"></caigouXiaoshouInfo>
  </div>
</template>

<script>
import h5Dialog from "@/components/h5Dialog.vue";
import editRemarkDialog from "./components/editRemarkDialog.vue";
// import sendGoodsDialog from "./components/sendGoods.vue";
import cancelOrderSure from "./components/cancelOrderSure.vue";
import querenshouhuo from "./components/querenshouhuo.vue";
import payEdit from "./components/payEdit.vue";
import editPrice from "./components/editPrice.vue";
// import msgHistory from "../../qunxinxi/msgHistory/index.vue";
import afterSellAdd from "./components/afterSellAdd.vue";
import afterSellViewBuyer from "../saleAfterOrder/components/afterSellView.vue";
// import orderDetail from "./components/orderDetail.vue";
import orderDetailDialog from "./components/orderDetailDialog";
import orderApi from "@/api/pickUp/order.js";
import kefuList from "@/components/common/kefuList.vue";
import peifuAdd from "./components/peifuAdd.vue";
import caiGouShouHouMX from "./components/caiGouShouHouMX.vue";
import otherChannels from "@/api/retrieveManage/otherChannels"

// 销售信息弹窗
import caigouXiaoshouInfo from "./components/caigouXiaoshouInfo.vue";

export default {
  name: "Caigoudingdan",
  components: {
    h5Dialog,
    cancelOrderSure,
    orderDetailDialog,
    editPrice,
    querenshouhuo,
    payEdit,
    afterSellAdd,
    afterSellViewBuyer,
    editRemarkDialog,
    kefuList,
    peifuAdd,
    caiGouShouHouMX,
    caigouXiaoshouInfo
  },
  data() {
    return {
      timer1: [],
      timer2: [],
      timer3: [],
      showMsgHis: false, //显示历史消息
      toGroups: "", //历史消息群id
      // 提号时间，商品ID 游戏类型 区服 实名状态   游戏账号【对应的商品链接】
      tableData: {
        records: [],
        total: 0,
      },
      btnLoading: false,
      loading: false,
      actived:'',
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderStatus: '',
        account: null,
        accountId: null,
        tel: null,
        dataType: "all",
      },
      copyVlaue: "",
      retailDomainList: [],
      IMhost: "",
      qudaoList:[]
    };
  },
  computed: {
    tenantList() {
      return this.$store.getters.tenantList;
    },
    allYouzhiMap() {
      return this.$store.getters.allYouzhiMap;
    },
    shopInfo() {
      return this.$store.getters.shopInfo;
    },
  },
  created() {
    if (this.$router.currentRoute.query.orderStatus) {
      this.actived = this.$router.currentRoute.query.orderStatus;
      this.queryParams.orderStatus =
        this.$router.currentRoute.query.orderStatus;
    }
    this.getList();
    this.getQudaoList()
  },
  // activated() {
  //   if (this.$router.currentRoute.query.orderStatus) {
  //     this.actived = this.$router.currentRoute.query.orderStatus;
  //     this.queryParams.orderStatus =
  //       this.$router.currentRoute.query.orderStatus;
  //   }
  //   this.getList();
  // },
  methods: {
  
     // 查询自定义平台渠道
     getQudaoList() {
        otherChannels.getQudaoList({
            isPage: 2,
            type: 2,
            pageNum: 1,
            pageSize: 100
        }).then((response) => {
            this.qudaoList = response.rows;
        });
    },
    // 打开销售信息弹窗
    openSaleInfo(row){
      this.$refs.caigouXiaoshouInfo.open(row)
    },
    // 联系客服
    openIM(tenantId) {
      // 打开客服列表
      this.$refs.kefuList.open(tenantId, 1);
    },
    // 跳转客服系统
    goIM(IMid, chatType) {
      // let token = Cookies.get("Admin-Token");
      let obj = {
        type: "goChat",
        hxusername: IMid,
        chatType: chatType,
      };
      // 告诉IM系统，需要跳转聊天页
      this.$store.dispatch("postMsgToIM", obj);
    },

    // 进入群组会话
    groupChat(row) {
      //       if (window.frames.length > 0) {
      //   //console.log("当前窗口有子窗口");
      // } else {
      //   //console.log("当前窗口没有子窗口");
      // }

      // 获取群组hxid
      orderApi
        .getToGroup({
          id: row.id,
        })
        .then((res) => {
          //console.log("%c Line:404 🥒 res", "color:#93c0a4", res);
          if (res.code == 200 && res.data.del == 1) {
            this.goIM(res.data.toGroup, "groupChat");
          } else {
            this.$message.error("未创建群组，请先创建群组!");
          }
        });
    },
    // 一键建群
    onKeyGroup(row) {
      /**卖家：${
        row.supplyChannel
      }<br/> */
      let str = `买家：${row.saleChannel}<br/>订单状态：${
        this.commonMaps.orderStatusMap[row.orderStatus]
      }<br/>商品编号：${row.goodsId}<br/>商品类型：${
        row.gameName
      }<br/>支付金额：${row.actualAmount}`;
      this.$confirm(str, "一键拉群", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        dangerouslyUseHTMLString: true,
      })
        .then(() => {
          let obj = {
            id: row.id,
          };
          orderApi.pullGroup(obj).then((res) => {
            this.$message(res.msg);
            if (res.code == 200) {
              this.getList();
              // 跳转到群聊
              this.goIM(res.data.toGroup, "groupChat");
            }
          });
        })
        .catch(() => {});
    },
    // 解散群组
    cancelGroup(id) {
      this.$confirm("确定解散该群组吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let obj = {
            id: id,
          };
          orderApi.cancelGroup(obj).then((res) => {
            this.$message(res.msg);
            if (res.code == 200) {
              this.getList();
            }
          });
        })
        .catch(() => {});
    },
    // 恢复群组
    recoverGroup(id) {
      this.$confirm("确定恢复该群组吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let obj = {
            id: id,
          };
          orderApi.recoveryGroup(obj).then((res) => {
            this.$message.success(res.msg);
            if (res.code == 200) {
              this.getList();
              this.goIM(res.data.toGroup, "groupChat");
            }
          });
        })
        .catch(() => {});
    },
    // 打开历史消息
    openMsgHis(row) {
      // 获取群组hxid
      orderApi
        .getToGroup({
          id: row.id,
        })
        .then((res) => {
          //console.log("%c Line:404 🥒 res", "color:#93c0a4", res);
          if (res.code == 200) {
            this.toGroups = res.data.toGroup;
            this.showMsgHis = true;
          } else {
            this.$message.error("未找到群组");
          }
        });
    },
    // 关闭历史消息
    guanbi() {
      this.showMsgHis = false;
    },

    // 获取列表
    getList() {
      // queryParams 请求列表
      // 创建时间
      if (this.timer1 && this.timer1.length) {
        this.queryParams.createTimeStart = this.timer1[0];
        this.queryParams.createTimeEnd = this.timer1[1] + " " + "23:59:59";
      } else {
        this.queryParams.createTimeStart = "";
        this.queryParams.createTimeEnd = "";
      }
      //支付时间
      if (this.timer2 && this.timer2.length) {
        this.queryParams.payTimeStart = this.timer2[0];
        this.queryParams.payTimeEnd = this.timer2[1] + " " + "23:59:59";
      } else {
        this.queryParams.payTimeStart = "";
        this.queryParams.payTimeEnd = "";
      }
      //完成时间
      if (this.timer3 && this.timer3.length) {
        this.queryParams.finishTimeStart = this.timer3[0];
        this.queryParams.finishTimeEnd =this.timer3[1].length>10?this.timer3[1]: (this.timer3[1] + " " + "23:59:59");
      } else {
        this.queryParams.finishTimeStart = "";
        this.queryParams.finishTimeEnd = "";
      }
      this.loading = true;
      this.queryParams.type = 2;
      orderApi.caigoudingdanList(this.queryParams).then((res) => {
        this.loading = false;
        this.tableData.records = res.rows;
        this.tableData.total = res.total;
      });
    },
    // tabs切换时触发
    tabChange() {
      this.queryParams.pageNum = 1;
      this.queryParams.orderStatus = this.actived;
      if (this.actived == "101") {
        // 售后
        this.queryParams.orderStatus = "";
        this.queryParams.afterSaleState = 100;
      } else {
        this.queryParams.afterSaleState = "";
      }
      this.getList();
    },
    // 复制成功和失败的方法
    onCopy(e) {
      this.$modal.msgSuccess("复制成功");
      this.copyVlaue = "";
    },
    onError() {
      this.$modal.msgError("复制失败");
      this.copyVlaue = "";
    },
    // 查看售后明细
    openShouhou(row) {
      this.$refs.caiGouShouHouMX.open(row.id, "buyer2");
    },
    //查看订单详情
    goOrderDetail(row) {
      this.$refs.orderDetailDialog.open(row.id, "buyer2");
    },
    // 复制订单信息
    copyOrder(row) {
      // let link = this.PChost +'/pages/order/orderDetail?orderId='+row.id
      let str = `订单编号：${row.no}\n商品编号：${row.goodsId}\n游戏：${
        row.gameName
      }\n区服：${row.qufu}\n简介：${row.des.slice(0, 120)}\n图片：${
        row.titleImg
      }\n官方客服：${row.saleUserNickname}`;
      this.$copyText(str).then(() => {
        this.$message.success("已复制到剪切板");
      });
    },
    // // 打开发货弹窗
    // sendGoods(row){
    //   // this.showSendDialog = true
    //   this.$refs.sendGoodsDialog.open(row)
    // },
    // // 编辑发货信息
    // editSendGoods(row,flag){
    //   this.$refs.sendGoodsDialog.open(row,flag)
    // },
    // 转到交易中
    transJiaoYiZhong(id) {
      this.$confirm("确认将该订单转为交易中吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          orderApi.changeOrderStatus({ id: id }).then((res) => {
            this.$message({
              type: "success",
              message: "操作成功!",
            });
            this.getList();
          });
        })
        .catch(() => {});
    },
    // 更改支付状态
    editPayStatus(row) {
      this.$refs.payEdit.open(row, "kefu");
    },
    // 取消订单
    cancelOrder(row) {
      // this.$refs.cancelOrderSure.open(row, "buyer2");
      this.$confirm("确认取消订单吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          orderApi
            .cancelOrder({
              remark: "买家取消",
              type: 2,
              id: row.id,
            })
            .then((res) => {
              this.$message({
                type: "success",
                message: "操作成功!",
              });
              this.getList();
            })
            .catch((err) => {
              this.loading = false;
            });
        })
        .catch(() => {});
    },
    // 编辑价格
    editPrice(row) {
      this.$refs.editPrice.open(row);
    },
    // 编辑备注
    editRemark(row) {
      this.$refs.editRemarkDialog.open(row);
    },
    // 完成订单
    completion(row) {
      if(row.salePay!=2){
        return this.$message.error('该订单未支付,请先支付!')
      }
      this.$refs.querenshouhuo.open({ ...row });
    },

    // 申请售后
    afterSale(row) {
      this.$refs.afterSellAdd.open(row, "buyer");
    },
    // 查看售后
    afterSaleView(id) {
      this.$refs.afterSellViewBuyer.open(id);
    },
    // 申请赔付
    addPeifuFn(row) {
      this.$refs.peifuAdd.open(row, "caigou");
    },
    resetQuery() {
      this.timer1 = [];
      this.timer2 = [];
      this.timer3 = [];
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        orderStatus: this.queryParams.orderStatus,
        dataType: "all",
        account: null,
        accountId: null,
        tel: null,
      };
      this.getList();
    },
    // 查看换绑信息
    changeInfo(row) {
      this.$refs.detailDialog.open(row.id);
    },
    // 每页条数改变
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },
    // 页码改变
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },
    exportOrder() {},
  },
};
</script>
<style lang="scss" scoped>
.link {
  color: blue;
  cursor: pointer;
}
</style>
